package dockyin.creative.pattern.prototype;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;

public class Prototype implements Cloneable, Serializable {

    private static final long serialVersionUID = 1L;

    private static final int MAX_SEEDS_SIZE = 10;

    private List<Long> seeds;

    public Prototype() {
        seeds = new ArrayList<>();
        SecureRandom random;
        try {
            random = SecureRandom.getInstance("SHA1PRNG");
        } catch (NoSuchAlgorithmException e) {
            System.out.println("Cannot get random generator.");
            return;
        }

        for (int i = 0; i < MAX_SEEDS_SIZE; i++) {
            seeds.add(random.nextLong());
        }
    }

    public String getSeeds() {
        if (null == seeds) {
            System.out.println("construct failed.");
        }
        return seeds.toString();
    }

    public Prototype clone() throws CloneNotSupportedException {
        return (Prototype) super.clone();
    }

    public Prototype deepClone() throws IOException, ClassNotFoundException {
         /* 写入当前对象的二进制流 */
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(this);

        /* 读出二进制流产生的新对象 */
        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bis);
        return (Prototype) ois.readObject();
    }
}
